package com.xyhuo.leetcode.november;

/**
 * 下降路径最小和
 * https://leetcode.cn/problems/minimum-falling-path-sum
 *
 * @time 2023/11/23
 */
public class MinFallingPathSum {

    public int minFallingPathSum(int[][] matrix) {
        int n = matrix.length;
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int leftVal = j - 1 >= 0 ? dp[i - 1][j - 1] : 100000;
                int rightVal = j + 1 < n ? dp[i - 1][j + 1] : 100000;
                dp[i][j] = Math.min(Math.min(leftVal, rightVal), dp[i - 1][j]) + matrix[i][j];
            }
        }
        int result = dp[n - 1][0];
        for (int i = 1; i < n; i++) {
            if (dp[n - 1][i] < result) {
                result = dp[n - 1][i];
            }
        }
        return result;
    }
}
